<template>
	<ContentWrap>
		<!-- 搜索工作栏 -->
		<el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
			<el-form-item label="中间件" prop="netSysId">
				<el-select v-model="queryParams.netSysId" placeholder="中间件" class="!w-240px" clearable>
					<el-option v-for="n in sysConfigList" :key="n.id" :label="n.community.name" :value="n.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="支付状态" prop="status">
				<el-select v-model="queryParams.status" placeholder="支付状态" :clearable="true" class="!w-120px">
					<el-option v-for="dict in unionMiniPayStatus" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="下发状态" prop="downNetFlag">
				<el-select v-model="queryParams.downNetFlag" placeholder="请选择下发状态" clearable class="!w-120px">
					<el-option v-for="dict in netDownFlags" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>

			<el-form-item label="时间区间">
				<el-date-picker
					v-model="successTime"
					type="daterange"
					:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
					value-format="YYYY-MM-DD HH:mm:ss"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					@change="changeTime" />
			</el-form-item>
			<el-form-item label="标题" prop="subject">
				<el-input v-model="queryParams.subject" placeholder="请输入标题" clearable @keyup.enter.stop="handleQuery" />
			</el-form-item>
			<el-form-item label="订单编号" prop="orderId">
				<el-input v-model="queryParams.orderId" placeholder="请输入订单编号" clearable @keyup.enter.stop="handleQuery" />
			</el-form-item>
			<el-form-item label="充值账号" prop="account">
				<el-input v-model="queryParams.account" placeholder="请输入充值账号" clearable @keyup.enter.stop="handleQuery" />
			</el-form-item>
			<el-form-item label="银联账户" prop="matCode">
				<el-input v-model="queryParams.matCode" placeholder="请输入银联账户" clearable @keyup.enter.stop="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
				<el-button type="success" plain :loading="exportLoading" @click="handleExport"> <Icon icon="ep:download" />导出</el-button>
			</el-form-item>
		</el-form>
	</ContentWrap>

	<!-- 列表 -->
	<ContentWrap>
		<el-table v-loading="loading" :data="list" :stripe="true">
			<el-table-column type="expand">
				<template #default="props">
					<div m="4">
						<p m="t-0 b-2">
							编号：<el-link type="primary" @click="getUnionPayInfo(props.row)">{{ props.row.orderId }}</el-link>
						</p>
						<p m="t-0 b-2">创建时间： {{ formatDate(props.row.createTime) }}</p>
						<p m="t-0 b-2">支付成功： {{ formatDate(props.row.successTime) }}</p>
						<p m="t-0 b-2">失效时间： {{ formatDate(props.row.expireTime) }}</p>
					</div>
				</template>
			</el-table-column>

			<el-table-column label="描述" align="left" min-width="280">
				<template #default="scope">
					<div>
						标题：<el-link type="primary" @click="showAddr(scope.row)">{{ scope.row.subject }}</el-link>
					</div>
					<div>
						地址：<el-link type="primary" @click="getUnionPayInfo(scope.row)">{{ scope.row.accountAddrOfLf }}</el-link>
					</div>
					<div>
						账号：

						<el-link type="success" @click="getMemberuser(scope.row.memberUserId)"> {{ scope.row.memberUserId }}（{{ scope.row.account }}）</el-link>
					</div>
					<div>
						命中规则：
						<el-link type="danger" v-if="scope.row.linkAccountMapId != null" @click="getHitRule(scope.row)">按楼栋分账</el-link>
						<el-link type="primary" v-else @click="getHitRule(scope.row)">按社区分账</el-link>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="金额(元)" align="center">
				<el-table-column label="金额" align="left" prop="amount" width="240">
					<template #default="scope">
						<template v-for="n in sysConfigList" :key="n.id + '_1'">
							<span v-if="n.id == scope.row.netSysId"> 中间件：{{ n.community.name }}</span>
						</template>
						<div style="font-weight: bold">支付金额：{{ divide(scope.row.amount, 100) }}</div>
						<div>
							兜底收入：{{ divide(scope.row.ownMemberMatBalance, 100) }} <span v-if="scope.row.refundStatus == 1" style="color: red">退款：{{ divide(scope.row.refundAmount, 100) }}</span>
						</div>
						<div>兜底账户：{{ scope.row.ownMemberMatCode }}</div>
					</template>
				</el-table-column>
				<el-table-column label="分账" align="left" prop="amount" width="250">
					<template #default="scope">
						<div style="font-weight: bold">分账账户1：{{ scope.row.divideMatCode1 }}</div>
						<div>分账1收入：{{ divide(scope.row.divideBalance1, 100) }}</div>
						<div style="font-weight: bold">分账账户2：{{ scope.row.divideMatCode2 }}</div>
						<div>分账2收入：{{ divide(scope.row.divideBalance2, 100) }}</div>
					</template>
				</el-table-column>
				<el-table-column label="手续费" align="left" prop="platformFeeRate" width="160">
					<template #default="scope">
						<div>平台手续费：{{ divide(scope.row.platformFeeAmount, 100) }}</div>
						<div>平台百分比：{{ scope.row.platformFeeRate }}%</div>
						<div>银联手续费：{{ divide(scope.row.channelFeeAmount, 100) }}</div>
						<div>银联百分比：{{ scope.row.channelFeeRate }}%</div>
					</template>
				</el-table-column>
			</el-table-column>
			<el-table-column label="状态" align="left" prop="status" width="90">
				<template #default="scope">
					<div><dict-tag :type="DICT_TYPE.UNION_MINI_PAY_STATUS" :value="scope.row.status" /></div>
					<div><dict-tag :type="DICT_TYPE.NET_DOWN_FLAG" :value="scope.row.downNetFlag" /></div>
				</template>
			</el-table-column>
			<el-table-column label="操作" class-name="fixed-width">
				<template #default="scope">
					<el-button link type="danger" v-if="scope.row.status == 9" @click="handleDelete(scope.row.id)" v-hasPermi="['zwsj:net-pay-order:delete']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页 -->
		<Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
	</ContentWrap>
</template>

<script setup lang="ts">
	import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
	import { formatDate } from '@/utils/formatTime'
	import { divide } from '@/utils/tools'
	import download from '@/utils/download'
	import { getNetSysConfig } from '@/api/zwsj/netSysConfig'
	import { NetAccountMapApi } from '@/api/zwsj/netaccountmap'
	import * as NetPayOrderApi from '@/api/zwsj/netPayOrder'
	import { getNetSysConfigs } from '@/api/zwsj/netSysConfig'
	import { getUser } from '@/api/member/user/index'
	import { ElNotification } from 'element-plus'

	defineOptions({ name: 'NetPayOrder' })

	const message = useMessage() // 消息弹窗
	const { t } = useI18n() // 国际化

	const loading = ref(true) // 列表的加载中
	const total = ref(0) // 列表的总页数
	const list = ref([]) // 列表的数据
	const queryParams = reactive({
		pageNo: 1,
		pageSize: 10,
		matCode: null,
		memberUserId: null,
		subject: null,
		orderId: null,
		account: null,
		status: null,
		downNetFlag: null,
		startDay: null,
		endDay: null,
	})
	const unionMiniPayStatus = getIntDictOptions(DICT_TYPE.UNION_MINI_PAY_STATUS)
	const netDownFlags = getIntDictOptions(DICT_TYPE.NET_DOWN_FLAG)

	const queryFormRef = ref() // 搜索的表单
	const exportLoading = ref(false) // 导出的加载中
	const sysConfigList = ref([])
	const successTime = ref()
	/** 查询列表 */
	const getList = async () => {
		loading.value = true
		try {
			const data = await NetPayOrderApi.getNetPayOrderPage(queryParams)
			list.value = data.list
			total.value = data.total
		} finally {
			loading.value = false
		}
	}

	/** 搜索按钮操作 */
	const handleQuery = () => {
		queryParams.pageNo = 1
		getList()
	}

	/** 重置按钮操作 */
	const resetQuery = () => {
		queryFormRef.value.resetFields()
		handleQuery()
	}

	/** 删除按钮操作 */
	const handleDelete = async (id: number) => {
		try {
			// 删除的二次确认
			await message.delConfirm()
			// 发起删除
			await NetPayOrderApi.deleteNetPayOrder(id)
			message.success(t('common.delSuccess'))
			// 刷新列表
			await getList()
		} catch {}
	}

	/** 导出按钮操作 */
	const handleExport = async () => {
		try {
			// 导出的二次确认
			await message.exportConfirm()
			// 发起导出
			exportLoading.value = true
			const data = await NetPayOrderApi.exportNetPayOrder(queryParams)
			download.excel(data, '宽带充值订单.xls')
		} catch {
		} finally {
			exportLoading.value = false
		}
	}

	const getUnionPayInfo = async (row: any) => {
		const id = row.id
		const data = await NetPayOrderApi.getUnionMiniPayOrderInfo(id)
		ElNotification({
			title: `订单状态：${data.status}`,
			message: h('i', { style: 'color: teal' }, `订单号：${data.merOrderId}`),
		})
	}

	const getMemberuser = async (memberUserId: number) => {
		const data = await getUser(memberUserId)
		ElNotification({
			title: `人员姓名：${data.nickname}`,
			message: h('i', { style: 'color: teal' }, `手机号码：${data.mobile}`),
		})
	}

	const showAddr = async (row: any) => {
		ElNotification({
			title: `充值地址`,
			message: h('i', { style: 'color: teal' }, `${row.accountAddrOfLf}`),
		})
	}

	const getHitRule = async (row: any) => {
		let linkAccountMapId = row.linkAccountMapId || null
		let linkSystemId = row.linkSystemId || null

		if (null != linkAccountMapId) {
			//查询按楼栋分账规则
			const data = await NetAccountMapApi.getNetAccountMap(linkAccountMapId)
			if (data != null) {
				let divideModeTxt = await makeDivideModeTxt(data.divideMode)
				let msg = '地址：' + data.addrRemark + '<br>'
				msg += '分账模式：' + divideModeTxt + '<br>'
				if (data.divideMatId1 != null) {
					msg += '账户1：' + data.divideMatUserName1_ + '(值：' + data.divideMatValue1 + ')<br>'
				}
				if (data.divideMatId2 != null) {
					msg += '账户2：' + data.divideMatUserName2_ + '(值：' + data.divideMatValue2 + ')<br>'
				}
				msg += '兜底：' + data.underTakeMatCode
				ElNotification({
					dangerouslyUseHTMLString: true, // 需要设置为 true 来允许 message 属性中的 HTML
					title: `分账规则`,
					message: msg,
					customClass: 'custom-notification',
				})
			}
		} else if (null != linkSystemId) {
			//查询按社区分账规则
			const data = await getNetSysConfig(linkSystemId)
			if (data != null) {
				let divideModeTxt = await makeDivideModeTxt(data.divideMode)
				let msg = '分账模式：' + divideModeTxt + '<br>'
				if (data.divideMatId1 != null) {
					msg += '账户1：' + data.divideMatUserName1_ + '(值：' + data.divideMatValue1 + ')<br>'
				}
				if (data.divideMatId2 != null) {
					msg += '账户2：' + data.divideMatUserName2_ + '(值：' + data.divideMatValue2 + ')<br>'
				}
				msg += '兜底：' + data.underTakeMatCode
				ElNotification({
					dangerouslyUseHTMLString: true, // 需要设置为 true 来允许 message 属性中的 HTML
					title: `分账规则`,
					message: msg,
					customClass: 'custom-notification',
				})
			}
		}
	}

	const makeDivideModeTxt = async (divideMode: number) => {
		let netDivideModes = getIntDictOptions(DICT_TYPE.NET_DIVIDE_MODE)
		let findRtn = netDivideModes.find(n => n.value == divideMode)
		if (findRtn != undefined && findRtn != null) {
			return findRtn.label
		}
	}

	const changeTime = async (timeArr: string) => {
		successTime.value = timeArr
		if (timeArr) {
			queryParams.startDay = timeArr[0]
			queryParams.endDay = timeArr[1]
		} else {
			queryParams.startDay = null
			queryParams.endDay = null
		}
	}

	/** 初始化 **/
	onMounted(() => {
		getNetSysConfigs().then(data => {
			sysConfigList.value = data
		})
		getList()
	})
</script>

<style scoped>
	.custom-notification {
		width: 500px; /* 设置您想要的宽度 */
	}
</style>
